<template>
	<view class="content">
		<!-- 单独区块元素 -->
		<view class="block">
			<!-- 应用总览 -->
			<view class="flex">
				<!-- 校园活动 -->
				<view class="activity" @click="gotoActivity">
					<view class="icon-a">
						<image src="../../static/images/icon_shcoolActivity.png" mode="aspectFit" class="img"></image>
					</view>
					<view class="icon-text">校园活动</view>
				</view>
				<!-- 二手交易 -->
				<navigator class="activity pl-30" url="/pages/index/circle/circle">
					<view class="icon-a">
						<image src="../../static/images/icon_circle.png" mode="aspectFit" class="img"></image>
					</view>
					<view class="icon-text">二手交易</view>
				</navigator>
				<!-- 通告 -->
				<view class="activity pl-30" @click="isNoticeShow()">
					<view class="icon-a">
						<image src="../../static/images/icon_notice.png" mode="aspectFit" class="img"></image>
					</view>
					<view class="icon-text text-center">通告</view>
				</view>
			</view>
		</view>
		<!-- 动态区块 -->
		<view class="block mt-30">
			<view class="blod-text">最新动态</view>
			<view class="selected mt-10 ml-30"></view>
			<!-- 文章类别选择 -->
			<scroll-view scroll-x="true" class="nav-scroll mt-30">
				<view v-for="(item, index) in navItems" :key="index" class="nav-item mr-30"
					:class="{ active: item.active }" @click="handleItemClick(index)">
					{{ item.name }}
				</view>
			</scroll-view>
			<!-- 活动模块 -->
			<view class="activity-content mt-50" v-for="(item, index) in choose_content" :key="index">
				<!-- 基础信息，包含头像以及姓名学校等 -->
				<view class="flex-space">
					<view class="flex">
						<view class="user-icon">
							<image :src="item.user_img" mode="aspectFill" class="img"></image>
						</view>
						<view class="infon-box ml-10">
							<view class="user-name">{{item.user_name}}</view>
							<view class="tips-text mt-10">{{item.school}}</view>
						</view>
					</view>
					<view class="time-text a-center">{{item.time}}</view>
				</view>
				<!-- 活动标题 -->
				<view class="blod-text mt-10" @click="gotoDetails(item)">{{item.title}}</view>
				<!-- 封面图片 -->
				<view class="cover" @click="gotoDetails(item)">
					<image :src="item.img_list[0]" mode="aspectFill" class="img"></image>
				</view>
				<!-- 活动内容 -->
				<view class="content-text mt-10 text-overflow-3" @click="gotoDetails(item)">{{item.content}}</view>
				<!-- 内容标签以及状态 -->
				<view class="flex-space mt-30">
					<uv-tags :text="item.type" size="mini"></uv-tags>
					<view class="flex">
						<uv-icon size="23" name="more-circle" color="primary"></uv-icon>
						<view class="blue-text ml-10">评论 {{item.number_comments || 0}}</view>
						<uv-icon size="23" name="thumb-up" v-if="!item.is_like" @click="isLike(item)"
							color="primary"></uv-icon>
						<uv-icon size="23" name="thumb-up-fill" v-if="item.is_like" @click="isLike(item)"
							color="primary"></uv-icon>
						<view class="blue-text ml-10" @click="isLike(item)">{{item.num_likes}}</view>
					</view>
				</view>
			</view>
			<!-- 刷新提示 -->
			<!-- <view class="mt-50 tips-text text-center mb-30">没有更多了~</view> -->
		</view>
		<!-- 加载更多 -->
		<view class="loading-more" v-if="hasMore">
			<uv-loading v-if="loading"></uv-loading>
			<text v-else @click="loadMore">加载更多</text>
		</view>
		<view v-else class="no-more">没有更多数据了</view>
		<!-- 发布内容按钮 -->
		<navigator class="give-activity" url="/pages/index/release/release">发布</navigator>
	</view>
	<!-- 通知通告部分 -->
	<uv-overlay :show="noticeShow" @click="noticeShow = false">
		<view class="warp">
			<view class="rect" @tap.stop>
				<view class="blod-text j-center">作者通告第六期</view>
				<view class="mt-30">现在是测试版本2.3，新增校园活动发布、点赞、收藏、评论等</view>
			</view>
		</view>
	</uv-overlay>
	<!-- 点赞提醒 -->
	<uv-toast ref="toast"></uv-toast>
	<view class="mask-login" @click="checkLoginStatus" v-show="!is_login"></view>
	<!-- 提示登录 -->
	<uv-overlay :show="show_login" @click="show_login = false">
		<view class="warp">
			<view class="rect" @tap.stop>
				<view class="blod-text">检测到还未登录</view>
				<div class="mt-30">
					<uv-button type="primary" text="现在登录" @click="gotoLogin"></uv-button>
				</div>
			</view>
		</view>
	</uv-overlay>
</template>

<script>
	import {
		filterSensitiveWords,
		formatDateTime
	} from '@/utils/utils.js'
	export default {
		data() {
			return {
				navItems: [{
						name: '全部',
						active: true
					},
					{
						name: '交友'
					},
					{
						name: '失物招领'
					},
					{
						name: '日常分享'
					},
					{
						name: '考研专区'
					},
					{
						name: '考公专区'
					},
					{
						name: '新生专区'
					}
				],
				noticeShow: false,
				choose_content: [],
				is_login: false, // 检查登录状态
				show_login: false, // 提示登录
				loading: false, // 加载状态
				hasMore: false, // 是否还有更多数据
				currentTab: 0, // 当前选择的标签
				user_info: {},
				tabList: ['全部', '交友', '失物招领', '日常分享', '考研专区', '考公专区', '新生专区'] // 标签列表
			}
		},
		methods: {
			// 将时间转换函数添加到methods中
			filterSensitiveWords,
			formatDateTime,
			// 类别条选择
			handleItemClick(index) {
				this.navItems.forEach((item, i) => {
					item.active = i === index;
				});
				// 根据选中的标签过滤 content_list
				this.currentTab = index
				const selectedCategory = this.navItems[index].name;
				console.log(selectedCategory)
				this.getArticles(selectedCategory)
			},
			// 显示通告
			isNoticeShow() {
				this.noticeShow = !this.noticeShow
			},
			// 查看文章详情
			gotoDetails(item) {
				const list = {
					article_id: item._id,
				}
				const data = encodeURIComponent(JSON.stringify(list))

				uni.navigateTo({
					url: `/pages/index/dynamic_details/dynamic_details?data=${data}`
				})
			},
			// 点赞数变更
			async update_likes_num(item, num_likes, bool) {
				const user_info = uni.getStorageSync('user_info')
				// 判断是点赞还是取消点赞
				if (bool) {
					item.user_likes_list.push(user_info._id)
				} else {
					const index = item.user_likes_list.indexOf(user_info._id)
					item.user_likes_list.splice(index, 1)
				}
				const db = uniCloud.database();
				const collection = db.collection('articles')
				const res = await collection.where({
					_id: item._id
				}).update({
					number_likes: num_likes,
					user_likes_list: item.user_likes_list
				})
			},
			// 点赞
			isLike(item) {
				if (item.is_like) {
					item.num_likes = item.num_likes - 1
					this.update_likes_num(item, item.num_likes, false)
					this.$refs.toast.show({
						type: 'warning',
						message: "取消点赞成功"
					})
				} else {
					item.num_likes = item.num_likes + 1
					this.update_likes_num(item, item.num_likes, true)
					this.$refs.toast.show({
						type: 'success',
						message: "点赞成功"
					})
				}
				item.is_like = !item.is_like
			},
			// 查看校园活动
			gotoActivity() {
				uni.navigateTo({
					url: '/pages/index/activity/activity'
				})
			},
			checkLoginStatus() {
				// 从本地缓存获取登录状态
				const loginStatus = uni.getStorageSync('is_login');
				// login不存在或者为false就是没登录
				if (loginStatus === false || loginStatus === "") {
					// 检测到还没登录
					this.show_login = true
				} else {
					this.is_login = true
				}
			},
			gotoLogin() {
				uni.navigateTo({
					url: '/pages/login/login'
				})
				this.show_login = false
			},
			// 获取文章内容
			async getArticles(selectedCategory) {
				const user_id = this.user_info._id
				if (this.loading) return;

				this.loading = true;
				try {
					const db = uniCloud.database();
					let res = {}
					if (selectedCategory === '全部') {
						res = await db.collection('articles').where({
							is_privacy: false,
						}).orderBy('createTime', 'desc').get()
					} else {
						res = await db.collection('articles').where({
							type: selectedCategory,
							is_privacy: false,
						}).orderBy('createTime', 'desc').get()
					}
					let list = res.result.data;
					console.log('11', list)
					// 判断是否已经点赞
					for (let i = 0; i < list.length; i++) {
						for (let j = 0; j < list[i].user_likes_list.length; j++) {
							if (list[i].user_likes_list[j] === this.user_info._id) {
								list[i].is_like = true
								break
							} else {
								list[i].is_like = false
							}
						}
						// 处理每篇文章的时间显示,点赞数量显示
						list = list.map(item => ({
							...item,
							time: this.formatDateTime(item.createTime),
							num_likes: item.number_likes,
						}))
					}
					this.choose_content = list
					const time = +Date.now()
					const timeStr = formatDateTime(time)
					await db.collection('user_info').doc(user_id).update({
						use_time: time,
						use_timeStr: timeStr
					})
				} catch (error) {
					console.error('获取文章失败:', error);
					uni.showToast({
						title: error.message || '获取文章失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
			async getUserInfo() {
				const db = uniCloud.database();
				const collection = db.collection('user_info')
				const res = await collection.doc(this.user_info._id).get()
				uni.setStorageSync('user_info', res.result.data[0])
			}
		},
		async onLoad() {
			const loginStatus = uni.getStorageSync('is_login')
			this.user_info = uni.getStorageSync('user_info')
			if (loginStatus === true) {
				this.is_login = true
			}
			await this.getUserInfo()
			await this.getArticles('全部')
			const mess = filterSensitiveWords('这是一段测试文本，包括关键词1')
			if (mess) {
				console.log('发现敏感词', mess)
			} else {
				console.log('没有敏感词')
			}
		},
	}
</script>

<style scoped>
	.content {
		padding: 20rpx;
		background-color: #e6e6e6;
	}

	.block {
		padding: 30rpx;
		background-color: #fff;
		border-radius: 20rpx;
		box-shadow: 0 0 2rpx #fff;
	}

	.icon-text {
		font-size: 25rpx;
	}

	.selected {
		width: 70rpx;
		height: 10rpx;
		background-color: orange;
		border-radius: 20rpx;
	}

	.content-text {
		font-size: 28rpx;
		font-weight: 400;
	}

	.nav-scroll {
		white-space: nowrap;
		overflow: hidden;
	}

	.nav-item {
		display: inline-block;
		padding: 10rpx;
		font-size: 26rpx;
		background-color: #ebebeb;
		cursor: pointer;
	}

	.nav-item.active {
		background-color: #ff9800;
		color: #fff;
	}

	.give-activity {
		width: 100rpx;
		height: 100rpx;
		border-radius: 100%;
		background-color: lightskyblue;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #fff;
		position: fixed;
		right: 30rpx;
		bottom: 100rpx;
	}

	.warp {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.rect {
		padding: 30rpx;
		width: 350rpx;
		background-color: #fff;
	}

	.mask-login {
		width: 100%;
		height: 100%;
		position: fixed;
		z-index: 999;
		top: 0;
		left: 0;
		background-color: (0, 0, 0, 0);
	}

	.loading-more {
		text-align: center;
		padding: 20rpx 0;
		color: #666;
		font-size: 28rpx;
	}

	.no-more {
		text-align: center;
		padding: 20rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	.info {
		font-size: 24rpx;
		color: #999;
		display: flex;
		align-items: center;
	}

	.info text {
		margin-right: 20rpx;
	}

	.time {
		color: #666;
	}
</style>